package com.nsi.service.Impl;

import com.google.gson.JsonObject;
import com.nsi.common.ResponseCode;
import com.nsi.exception.NsiOperationException;
import com.nsi.service.AccessTokenService;
import com.nsi.util.Httpsrequest;
import com.nsi.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author Luo Zhen
 * @create 2020-01-09 16:11
 */
@Slf4j
@Service
public class AccessTokenServiceImpl implements AccessTokenService {

    @Override
    public String getAccessToken(String appId, String secret) {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
        String responseJson;
        try {
            responseJson = Httpsrequest.httpsRequest(requestUrl, "GET", null);
            log.info("【获取小程序AccessToken】,}", responseJson);
        } catch (Exception e) {
            log.error("【获取小程序AccessToken失败】:{}", e);
            throw new NsiOperationException(ResponseCode.SERVER_ERROR.getDesc());
        }
        JsonObject jsonObject = JsonUtils.getJsonObject(responseJson);
        String accessToken = jsonObject.get("access_token").getAsString();
        String expires_in = jsonObject.get("expires_in").getAsString();
        log.info("expires_in:"+expires_in);
        return accessToken;
    }
}
